<template>
  <div class="shortcut-input">
    <el-input
      :model-value="displayValue"
      placeholder="请按下快捷键 (Ctrl/Alt/Shift + 字母/数字)"
      readonly
      @focus="startListening"
      @blur="stopListening"
    >
      <template #append>
        <el-button v-if="displayValue" @click="clearShortcut" type="danger" plain> 清空 </el-button>
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'

/**
 * Props & Emits
 */
const props = defineProps<{
  modelValue?: string
}>()

const emits = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

/**
 * 内部状态
 */
const displayValue = ref<string>(props.modelValue || '')
const shortcutKeys = ref<string[]>([])

let listening = false

/**
 * 同步外部 v-model
 */
watch(
  () => props.modelValue,
  (val) => {
    if (val !== displayValue.value) {
      displayValue.value = val || ''
    }
  }
)

/**
 * 事件处理
 */
const startListening = () => {
  if (listening) return
  listening = true
  window.addEventListener('keydown', handleKeydown)
}

const stopListening = () => {
  if (!listening) return
  listening = false
  window.removeEventListener('keydown', handleKeydown)
}

const handleKeydown = (e: KeyboardEvent) => {
  e.preventDefault()

  const keys: string[] = []
  if (e.ctrlKey) keys.push('Ctrl')
  if (e.shiftKey) keys.push('Shift')
  if (e.altKey) keys.push('Alt')
  if (e.metaKey) keys.push('Meta') // Mac Command

  let mainKey = ''

  // ✅ 用 event.code 识别字母和数字
  if (/^Key[A-Z]$/.test(e.code)) {
    mainKey = e.code.replace('Key', '').toUpperCase()
  } else if (/^Digit[0-9]$/.test(e.code)) {
    mainKey = e.code.replace('Digit', '')
  } else if (/^Numpad[0-9]$/.test(e.code)) {
    mainKey = e.code.replace('Numpad', '')
  }

  const hasModifier = e.ctrlKey || e.altKey || e.shiftKey || e.metaKey
  const isValidMainKey = !!mainKey

  if (!hasModifier || !isValidMainKey) {
    console.warn('非法快捷键，只能使用 Ctrl/Alt/Shift + 字母/数字')
    return
  }

  keys.push(mainKey)

  shortcutKeys.value = keys
  displayValue.value = keys.join(' + ')

  emits('update:modelValue', displayValue.value)
}

const clearShortcut = () => {
  shortcutKeys.value = []
  displayValue.value = ''
  emits('update:modelValue', '')
}
</script>

<style scoped>
.shortcut-input {
  width: 300px;
}
</style>
